<template>
  <div class='container-directorys'>
    <el-dialog
  title="新增技巧"
  :visible.sync="dialogVisible"
  width="30%"
  >
<el-form ref="refForm" :model="addform" label-width="80px" :rules="addrules">
  <el-form-item label="所属学科" v-if="!this.$route.query.id" prop="subjectID">
   <el-select v-model="addform.subjectID" style="width:100%">
     <el-option
     v-for="item in subjectList"
     :value="item.value"
     :label="item.label"
     :key="item.value"
     >
     </el-option>
   </el-select>
  </el-form-item>
   <el-form-item label="目录名称" prop="directoryName">
    <el-input v-model="addform.directoryName"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirm()">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import { simple as subjectList } from '@/api/hmmm/subjects.js'
import { update, add } from '@/api/hmmm/directorys.js'
export default {
  name: 'DirectoryAdd',
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      dialogVisible: false,
      addform: {
        id: null,
        directoryName: null,
        subjectID: null
      },
      addrules: {
        subjectID: [{ type: 'number', message: '请选择所属学科', tirgger: 'blur' }],
        directoryName: [{ required: true, message: '请输入目录名称', tirgger: 'blur' }]
      },
      subjectList: []// 学科列表数据
    }
  },
  async created () {
    const { data } = await subjectList()
    this.subjectList = data
  },
  methods: {
    open () {
      this.dialogVisible = true
      // 如果有id就是修改
      if (this.data.id) {
        // 把data里的数据解构出来赋值给addform
        const { id, directoryName, subjectID } = this.data
        this.addform = { id, directoryName, subjectID }
      } else {
        this.addform = {
          id: null,
          directoryName: null,
          subjectID: +this.$route.query.id || null
        }
        // 清除检验效果
        this.$nextTick(() => {
          this.$refs.refForm.clearValidate()
        })
      }
    },
    // 确定
    confirm () {
      this.$refs.refForm.validate(async valid => {
        if (valid) {
          if (!this.data.id) {
            // 新增
            await add(this.addform)
          } else {
            // 修改
            this.addform.id = this.data.id
            await update(this.addform)
          }
          this.$message.success('操作成功')
          // 关闭对话框
          this.dialogVisible = false
          // 通知父组件重新渲染
          this.$emit('updateList')
        }
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
